<template>
  <div class="shopcar-container">
    <!-- 添加收货地址(显示条件：没有地址 && 购物车非空) -->
    <div>{{ $store.selectAddressInfo }}</div>
    <van-contact-card
      v-if="hasAddress === false && !isCarEmpty"
      @click="selectAddress"
      type="add"
      add-text="选择收货地址"
    />

    <!-- v-if="hasAddress && !isCarEmpty"  -->
    <!-- 显示收货地址(显示条件:有地址 && 购物车非空) -->
    <div @click="selectAddress" class="address" v-if="hasAddress && !isCarEmpty">
      <div class="info">
        <div class="icon">
          <van-icon name="logistics" />
        </div>
        <div class="area">
          <div class="province">
            {{ selectAddressInfo.province + selectAddressInfo.city + selectAddressInfo.county }}
            <van-tag v-if="selectAddressInfo.isDefault" color="#ee0a24">默认</van-tag>
          </div>
          <div class="street">{{ selectAddressInfo.addressDetail }}</div>
          <div class="tel">{{ selectAddressInfo.name }} {{ selectAddressInfo.tel }}</div>
        </div>
      </div>
      <div>
        <van-icon name="arrow" />
      </div>

      <div class="line">
        <div v-for="i in 10" :key="i" :class="['item', 'bg' + (i % 2) + 1]"></div>
      </div>
    </div>

    <!-- 购物车商品列表 -->
    <div class="car">
      <div class="item" v-for="item in goodsList" :key="item.id">
        <div>
          <van-checkbox
            @click="changeSelected(item.id)"
            v-model="$store.getters.getGoodsSelected[item.id]"
            checked-color="#ee0a24"
          />
        </div>

        <div class="thumb-image">
          <img :src="item.thumb_path" />
        </div>

        <div class="info">
          <div class="title">{{ item.title }}</div>
          <div class="footer">
            <div class="price">&yen;{{ item.sell_price }}</div>
            <van-stepper
              @change="changeNumber(item.id, $event)"
              class="number"
              v-model="$store.getters.getGoodsNumber[item.id]"
            />
            <van-button size="small" type="danger" @click="delCarGoods(item.id)">删除</van-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 购物车空提示 -->
    <div class="empty-area" v-if="isCarEmpty">
      <div style="margin-top: 20px">
        <img width="110px" style="margin: 10px 0" src="@/assets/images/car.png" alt="" />
      </div>
      <span class="emptyInfo">购物车竟然是空的</span>
      <span style="overflow: hidden; line-height: 16px; text-overflow: ellipsis; white-space: nowrap"
        >再忙，也要记得买点什么犒赏自己~</span
      >

      <van-button @click="$router.push('/home')">去首页逛逛</van-button>
    </div>

    <!-- 结算付款(显示条件:购物车非空 && 有选中的购物车商品) -->
    <van-submit-bar
      v-if="!isCarEmpty"
      :disabled="!getCarSelectedGoodsIds"
      :price="getCarSelectedPrice"
      button-text="去结算付款"
      @submit="commitOrder"
    >
      <template #tip> 默认只支持微信支付 </template>
      <template #default> 共{{ getCarSelectedNumber }}件商品 </template>
    </van-submit-bar>
  </div>
</template>

<script>
import { reqCarGoods } from '@/api/user'
import { reqCommitOrder } from '@/api/order'

import { mapState, mapGetters } from 'vuex'
import { genOrderId } from '@/utils/tool'
export default {
  data() {
    return {
      goodsList: [],
    }
  },
  computed: {
    ...mapState(['selectAddressInfo', 'token']),
    ...mapGetters([
      'isCarEmpty',
      'getCarSelectedPrice',
      'getCarSelectedNumber',
      'hasAddress',
      'getCarSelectedGoodsIds',
    ]),
  },
  methods: {
    // 提交订单
    async commitOrder() {
      // 1. 是否选中了收货地址
      if (!this.selectAddressInfo.id) {
        this.$toast('亲，请先完善收货地址')
        return
      }

      // 2. 下单,准备订单参数
      let orderData = {
        order_id: genOrderId(),
        address_id: this.selectAddressInfo.id,
        total_price: this.getCarSelectedPrice / 100,
        number: this.getCarSelectedNumber,
        goods_ids: this.getCarSelectedGoodsIds,
      }
      let result = await reqCommitOrder(orderData)
      if (result.code === 20000) {
        this.$toast('生成订单成功')
        // 1. 清空购物车
        this.$store.commit('clearShopCar')
        // 2. 进入到订单详情页面
        this.$router.replace('/orderDetail/' + orderData.order_id)
      }
    },
    changeNumber(id, number) {
      this.$store.commit('setCarGoodsNumber', { id, number })
    },
    changeSelected(id) {
      this.$store.commit('setCarGoodsSelected', id)
    },
    delCarGoods(id) {
      this.$dialog
        .confirm({
          message: '确认删除吗',
          confirmButtonColor: '#ee0a24',
        })
        .then(async () => {
          this.$store.commit('delCarGoods', id)
          this.getCarGoods()
        })
        .catch(() => {})
    },
    selectAddress() {
      this.$router.push('/addresslist')
    },

    // 获取购物车商品
    async getCarGoods() {
      if (!this.$store.getters.getCarGoodsIds) {
        // 购物车没有商品
        this.goodsList = []
        return []
      }
      let { message } = await reqCarGoods(this.$store.getters.getCarGoodsIds)
      this.goodsList = message
      return message
    },
  },
  async mounted() {
    // 获取购物车商品
    let carList = await this.getCarGoods()
    if (carList.length > 0) {
      // 购物车有商品，才获取用户收货地址
      if (!this.$store.state.selectAddressInfo.id) {
        this.$store.dispatch('getUserAddress')
      }
    }
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'goodsdetail') {
      // 控制返回按钮显隐
      to.meta.isShowBackIcon = true
    } else {
      to.meta.isShowBackIcon = false
    }

    next()
  },
}
</script>

<style lang="scss" scoped>
.shopcar-container {
  height: 100vh;
  padding: 4px;
  background-color: #f2f2f2;

  .van-dialog {
    text-align: center;
  }

  .address {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 14px 6px;
    background-color: #fff;
    border-radius: 8px;

    .info {
      display: flex;
      align-items: center;

      .area {
        display: flex;
        flex-direction: column;
        font-size: 14px;

        .street {
          padding: 4px 0;
          font-weight: 700;
        }
      }

      .icon {
        margin-right: 10px;
        font-size: 26px;
        color: red;
      }
    }

    .line {
      position: absolute;
      right: 0;
      bottom: 0;
      display: flex;
      justify-content: space-evenly;
      width: 100%;
      padding: 2px;

      .item {
        width: 14px;
        height: 5px;
        margin: 0;
        transform: skewX(-45deg);
      }

      .bg1 {
        background-color: rgb(12 171 234);
      }

      .bg2 {
        background-color: rgb(226 13 13);
      }
    }
  }

  .car {
    .item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10px;
      margin: 10px 0;
      background-color: #fff;
      border-radius: 8px;
    }

    .thumb-image {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 70px;
      margin: 0 4px;

      img {
        width: 100%;
      }
    }

    .info {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      height: 70px;

      .title {
        display: -webkit-box;
        overflow: hidden;
        font-size: 14px;
        text-overflow: ellipsis;
        line-clamp: 1;
        -webkit-box-orient: vertical;
      }

      .footer {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .price {
          color: #f00;
        }

        .van-button {
          width: 50px;
        }
      }
    }

    .van-cell {
      border-radius: 8px;
    }
  }

  .empty-area {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .emptyInfo {
      margin: 10px 0;
      font-size: 18px;
      color: #666;
      -webkit-font-smoothing: antialiased;
    }

    span {
      font-size: 13px;
      color: #999;
    }

    button {
      height: 40px;
      margin: 30px 0;
      color: #5f646e;
      background-color: #f2f2f2;
      border: 1px solid #ccc;
    }
  }

  .van-submit-bar {
    bottom: 50px;
  }
}
</style>
